package server_io;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class HttpServer {

    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";
    public static final String ROOT_PATH = HttpServer.class.getClassLoader().getResource("").getFile() + "static";
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private boolean shutdown = false;
    ExecutorService executorService = new ThreadPoolExecutor(2, 10, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(5, true), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        HttpServer server = new HttpServer();
        server.await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
        while (!shutdown) {
            try {
                Socket accept = serverSocket.accept();
                System.out.println("主线程接收到消息了:" + Thread.currentThread().getName());
                executorService.execute(() ->  handleMessage(accept) );
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    public void handleMessage(Socket socket) {
        InputStream input = null;
        OutputStream output = null;
        try {
            System.out.println(Thread.currentThread().getName() + "开始处理请求返回响应消息");
            input = socket.getInputStream();
            output = socket.getOutputStream();
            //create server_io.Request object and parse
            Request request = new Request(input);
            request.parse();
            if (request.getUri().contains(SHUTDOWN_COMMAND)) {
                shutdown = true;
            }
            //create server_io.Response object
            Response response = new Response(output);
            response.setRequest(request);
            response.sendStaticResource();
            socket.shutdownInput();
            socket.shutdownOutput();
            System.out.println(Thread.currentThread().getName() + ": Socket 通信已关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


